import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/users/Users'
import Role from '../components/authority/Role'
import Right from '../components/authority/Right'
import Goods from '../components/commodity/Goods'
import Params from '../components/commodity/Parameter'
import Categories from '../components/commodity/categories'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/roles', component: Role },
      { path: '/rights', component: Right },
      { path: '/goods', component: Goods },
      { path: '/params', component: Params },
      { path: '/categories', component: Categories }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂载路由守卫beforeeach
router.beforeEach((to, from, next) => {
  // to即将访问的路径
  // from从哪里跳转
  // 放行 两种方式：1 next()直接放行 2 next('/login')强制跳转
  // 如果用户处于登录状态，直接跳转
  if (to.path === '/login') return next()

  // 如果用户没有登录，即没有token强制跳转/login
  const tokenStr = window.sessionStorage.getItem('token')

  if (!tokenStr) return next('/login')
  next()
})

export default router
